<?php
/**
 * Created by PhpStorm.
 * User: rui
 * Date: 2018/7/21
 * Time: 下午5:33
 */

namespace app\api\controller;


use app\common\model\AccountBook;
use app\common\model\UserEquipments;
use think\db\Query;
use think\Exception;

class Account extends Base
{
    public function add()
    {
        $bankid = input('bank_id');
        $ueid = input('user_id');
        $name = input('name');
        $amount = input('amount');
        $settleTime = input('date');
        $remark = input('remark');
        try {
            $ue = UserEquipments::get(['equipment_id' => $ueid]);
            $data = [
                'bid' => $bankid
                , 'userid' => $ue->user_id
                , 'name' => $name
                , 'amount' => $amount
                , 'settleTime'=>$settleTime
                , 'remark' => $remark
            ];
            $ab = AccountBook::create($data);
            if ($ab){
                return $this->successInfo('成功创建消费记录',$ab);
            }
        }catch (Exception $exception){
            return $this->exceptionInfo($exception);
        }

    }

    public function getAccountBookList()
    {
        $bid = input('bid');
        $id = input('id');
        $where = [];
        if ($bid || $id) {
            $where = $bid?['bid' => $bid]:['account_book.id'=>$id];
        }else{
            $where['vo_account_book.userid'] = $this->user->userId;
        }
        $sdate = input('sdate');
        $edate = input('edate');
        $abModel = new AccountBook();
        if ($sdate){
            $where['createTime'] = ['between'=>[$sdate,$edate?:date(DateService::DATE_FORMART_STRING)]];
        }
        $ab = $abModel::all(function (Query $query) use ($where){
            $query->where($where)->order('id desc')->limit(input('size')?:10)->page(input('page')?:1);
        },'getBankList');
        if (!$ab){
            return $this->errorInfo('暂无数据');
        }
        $allAmount = $abModel->where($where)->sum('amount');
        return $this->getReturnInfo(1,'成功获取信息',['list'=>$ab,'allAmount'=>$allAmount]);
    }

    public function del()
    {
        $id = input('id');
        if (!$id){
            return $this->errorInfo('无效数据');
        }
        $ab = AccountBook::get(['id'=>$id,'userid'=>$this->user->userId]);
        if (!$ab){
            return $this->errorInfo('无权删除');
        }
        $r = $ab->delete();
        if ($r){
            return $this->successInfo('成功删除');
        }else{
            return $this->errorInfo('删除失败');
        }
    }

    public function update()
    {
        $id = input('id');
        $accountM = new AccountBook();
        $acc = $accountM::get($id);
        $r = $acc->save(input());
        if (!$r){
            return $this->errorInfo('修改失败');
        }else{
            return $this->successInfo('已成功修改');
        }
    }
}